package dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import dto.ChestionareDTO;
import dto.IntrebariDTO;
import entities.Chestionare;
import entities.Intrebari;

@Stateless
public class IntrebariDAO implements IntrebariDAORemote {

	@PersistenceContext
	EntityManager em;
	
	Conversion conv = new Conversion();

	@Override
	public void create(IntrebariDTO intrebari) {
		try {
			Intrebari i = new Intrebari();
			i.setIntrebare(intrebari.getIntrebare());
			i.setTip(intrebari.getTip());
			Chestionare c = new Chestionare();
			c.setActiv(intrebari.getChestionareDTO().getActiv());
			c.setCategorie(intrebari.getChestionareDTO().getCategorie());
			c.setId(intrebari.getChestionareDTO().getId());
			c.setNume(intrebari.getChestionareDTO().getNume());
			c.setSubcategorie(intrebari.getChestionareDTO().getSubcategorie());
			c.setScop(intrebari.getChestionareDTO().getScop());
			i.setChestionare(c);
			em.persist(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public List<IntrebariDTO> getIntrebariByChestionar(ChestionareDTO ch){
		
		Chestionare c = new Chestionare();
		c = conv.convertChestionareDTO(ch);
		Query query = em.createNamedQuery("getIntrebariByChestionarId");
		query.setParameter("ch_idParam", c);
		List<Intrebari> intrebari  = new ArrayList<Intrebari>();
		intrebari = query.getResultList();
		List<IntrebariDTO> intreb = new ArrayList<IntrebariDTO>();
		for (int i = 0; i < intrebari.size(); i++){
			IntrebariDTO iDTO = new IntrebariDTO();
			iDTO = conv.convertIntrebareToDTO(intrebari.get(i));
			intreb.add(iDTO);
		}
		return intreb;
	}

	@Override
	public List<IntrebariDTO> getIntrebariByChestionarId(int id) {
		Query query = em.createNamedQuery("getIntrebariByChestionarId");
		query.setParameter("ch_idParam", id);
		List<Intrebari> intrebari = query.getResultList();
		List<IntrebariDTO> intr = new ArrayList<IntrebariDTO>();
		for (int i = 0; i < intrebari.size(); i++) {
			IntrebariDTO in = new IntrebariDTO();
			in.setId(intrebari.get(i).getId());
			in.setTip(intrebari.get(i).getTip());
			in.setIntrebare(intrebari.get(i).getIntrebare());
			
			intr.add(in);
		}

		return intr;
	}

	@Override
	public void update(IntrebariDTO intrebariUpd) {
		Intrebari i = new Intrebari();
		i = em.find(Intrebari.class, intrebariUpd.getId());
		i.setIntrebare(intrebariUpd.getIntrebare());
		i.setTip(intrebariUpd.getTip());
		
	}

	@Override
	public void delete(IntrebariDTO intrebare) {
		int id = intrebare.getId();
		Intrebari i = new Intrebari();
		i = em.find(Intrebari.class, id);
		em.remove(i);
		
	}

}
